package com.xky.ui.module.inventorManagement.add;

import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.Date;

public class AddInvenTory extends JFrame {
    private JPanel contentPanel, formPanel, buttonPanel;
    private JTextField[] textFields;
    private JFormattedTextField expiryDateField;
    
    private static final Color BACKGROUND_COLOR = new Color(245, 248, 250);
    private static final Color ACCENT_COLOR = new Color(70, 130, 180);
    private static final Color BUTTON_COLOR = new Color(70, 130, 180);
    private static final Color TEXT_COLOR = new Color(50, 50, 80);
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 24);
    private static final Font LABEL_FONT = new Font("微软雅黑", Font.PLAIN, 14);
    private static final Font INPUT_FONT = new Font("微软雅黑", Font.PLAIN, 14);
    private static final Font BUTTON_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final int INPUT_HEIGHT = 30;

    public AddInvenTory() {
        setTitle("添加商品库存信息");
        setSize(550, 600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        initUI();
        setVisible(true);
    }

    private void initUI() {
        // 设置整体布局
        setLayout(new BorderLayout());
        contentPanel = new JPanel(new BorderLayout(0, 20));
        contentPanel.setBackground(BACKGROUND_COLOR);
        contentPanel.setBorder(new EmptyBorder(20, 30, 20, 30));
        
        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setBackground(BACKGROUND_COLOR);
        JLabel titleLabel = new JLabel("添加商品库存信息");
        titleLabel.setFont(TITLE_FONT);
        titleLabel.setForeground(ACCENT_COLOR);
        titlePanel.add(titleLabel);
        
        // 表单面板
        formPanel = new JPanel();
        formPanel.setLayout(new GridBagLayout());
        formPanel.setBackground(Color.WHITE);
        formPanel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
            BorderFactory.createEmptyBorder(20, 25, 20, 25)
        ));
        
        // 设置圆角面板
        formPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(getBackground());
                g2.fillRoundRect(0, 0, getWidth(), getHeight(), 15, 15);
                g2.dispose();
            }
        };
        formPanel.setOpaque(false);
        formPanel.setLayout(new GridBagLayout());
        formPanel.setBackground(Color.WHITE);
        formPanel.setBorder(BorderFactory.createEmptyBorder(20, 25, 20, 25));
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(8, 5, 8, 5);
        gbc.weightx = 1.0;
        
        // 创建表单字段
        String[] labelTexts = {
                "商品ID：",
                "仓库ID：",
                "当前库存数量：",
                "已分配数量：",
                "库位编码：",
                "批次号：",
                "过期日期："
        };
        
        textFields = new JTextField[6]; // 现在有6个文本字段
        
        for (int i = 0; i < labelTexts.length; i++) {
            JLabel label = new JLabel(labelTexts[i]);
            label.setFont(LABEL_FONT);
            label.setForeground(TEXT_COLOR);
            
            gbc.gridx = 0;
            gbc.gridy = i;
            gbc.gridwidth = 1;
            formPanel.add(label, gbc);
            
            if (i == 6) { // 过期日期
                expiryDateField = new JFormattedTextField(new SimpleDateFormat("yyyy-MM-dd"));
                expiryDateField.setValue(new Date());
                expiryDateField.setFont(INPUT_FONT);
                expiryDateField.setPreferredSize(new Dimension(250, INPUT_HEIGHT));
                expiryDateField.setToolTipText("格式: yyyy-MM-dd");
                
                // 添加日历选择按钮
                JPanel datePanel = new JPanel(new BorderLayout());
                datePanel.add(expiryDateField, BorderLayout.CENTER);
                
                JButton calendarButton = new JButton("📅");
                calendarButton.setPreferredSize(new Dimension(INPUT_HEIGHT, INPUT_HEIGHT));
                calendarButton.addActionListener(e -> showDatePicker());
                datePanel.add(calendarButton, BorderLayout.EAST);
                
                gbc.gridx = 1;
                formPanel.add(datePanel, gbc);
            } else {
                textFields[i] = new JTextField();
                textFields[i].setFont(INPUT_FONT);
                textFields[i].setPreferredSize(new Dimension(250, INPUT_HEIGHT));
                
                // 添加焦点监听器和提示
                setupTextField(textFields[i], getPlaceholder(i), getTooltip(i));
                
                gbc.gridx = 1;
                formPanel.add(textFields[i], gbc);
            }
        }
        
        // 按钮面板
        buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBackground(BACKGROUND_COLOR);
        
        JButton submitButton = createStyledButton("提交", BUTTON_COLOR);
        JButton resetButton = createStyledButton("重置", new Color(120, 120, 120));
        
        buttonPanel.add(submitButton);
        buttonPanel.add(resetButton);
        
        // 组装面板
        contentPanel.add(titlePanel, BorderLayout.NORTH);
        contentPanel.add(formPanel, BorderLayout.CENTER);
        contentPanel.add(buttonPanel, BorderLayout.SOUTH);
        add(contentPanel);
        
        // 按钮事件
        submitButton.addActionListener(e -> handleSubmit());
        resetButton.addActionListener(e -> handleReset());
    }
    
    private void setupTextField(JTextField textField, String placeholder, String tooltip) {
        textField.setForeground(Color.GRAY);
        textField.setText(placeholder);
        textField.setToolTipText(tooltip);
        
        textField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                if (textField.getText().equals(placeholder)) {
                    textField.setText("");
                    textField.setForeground(Color.BLACK);
                }
            }
            
            @Override
            public void focusLost(FocusEvent e) {
                if (textField.getText().isEmpty()) {
                    textField.setForeground(Color.GRAY);
                    textField.setText(placeholder);
                }
            }
        });
    }
    
    private String getPlaceholder(int fieldIndex) {
        switch (fieldIndex) {
            case 0: return "请输入商品ID";
            case 1: return "请输入仓库ID";
            case 2: return "请输入库存数量";
            case 3: return "请输入已分配数量";
            case 4: return "请输入库位编码";
            case 5: return "请输入批次号";
            default: return "";
        }
    }
    
    private String getTooltip(int fieldIndex) {
        switch (fieldIndex) {
            case 0: return "商品ID必须是正整数";
            case 1: return "仓库ID必须是正整数";
            case 2: return "库存数量必须为非负整数";
            case 3: return "已分配数量必须为非负整数，且不能超过库存数量";
            case 4: return "库位编码不能为空";
            case 5: return "批次号不能为空";
            default: return "";
        }
    }
    
    private JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text) {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(getBackground());
                g2.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
                g2.dispose();
                super.paintComponent(g);
            }
        };
        button.setOpaque(false);
        button.setContentAreaFilled(false);
        button.setBorderPainted(false);
        button.setFocusPainted(false);
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFont(BUTTON_FONT);
        button.setPreferredSize(new Dimension(120, 36));
        return button;
    }
    
    private void showDatePicker() {
        // 简单实现，实际项目中可以使用第三方日期选择器
        JOptionPane.showMessageDialog(this, "请在文本框中直接输入日期，格式为：yyyy-MM-dd", 
                "日期选择", JOptionPane.INFORMATION_MESSAGE);
    }
    

    
    private void handleSubmit() {
        try {
            // 获取并验证输入
            String productIdText = textFields[0].getText().trim();
            String warehouseIdText = textFields[1].getText().trim();
            String quantityText = textFields[2].getText().trim();
            String allocatedText = textFields[3].getText().trim();
            String locationCode = textFields[4].getText().trim();
            String batchNumber = textFields[5].getText().trim();
            String expiryDateStr = expiryDateField.getText().trim();
            
            // 检查占位符
            if (productIdText.equals(getPlaceholder(0))) productIdText = "";
            if (warehouseIdText.equals(getPlaceholder(1))) warehouseIdText = "";
            if (quantityText.equals(getPlaceholder(2))) quantityText = "";
            if (allocatedText.equals(getPlaceholder(3))) allocatedText = "";
            if (locationCode.equals(getPlaceholder(4))) locationCode = "";
            if (batchNumber.equals(getPlaceholder(5))) batchNumber = "";
            
            Integer productId = parseIntegerField(productIdText, "商品ID");
            Integer warehouseId = parseIntegerField(warehouseIdText, "仓库ID");
            Integer quantity = parseIntegerField(quantityText, "当前库存数量");
            Integer allocatedQuantity = parseIntegerField(allocatedText, "已分配数量");
            
            // 输入验证
            if (!validateInputs(productId, warehouseId, quantity,
                    allocatedQuantity, locationCode, batchNumber, expiryDateStr)) {
                return;
            }
            
            // 添加记录
            if (addProduct(productId, warehouseId, quantity,
                    allocatedQuantity, locationCode, batchNumber, expiryDateStr)) {
                JOptionPane.showMessageDialog(this, "商品库存信息添加成功！",
                        "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, "商品库存信息添加失败！",
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "发生错误: " + ex.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }
    
    private void handleReset() {
        for (int i = 0; i < textFields.length; i++) {
            textFields[i].setForeground(Color.GRAY);
            textFields[i].setText(getPlaceholder(i));
        }
        
        expiryDateField.setValue(new Date());
    }

    private Integer parseIntegerField(String text, String fieldName) throws NumberFormatException {
        if (text.isEmpty()) {
            throw new NumberFormatException(fieldName + "不能为空");
        }
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            throw new NumberFormatException(fieldName + "必须是有效的整数");
        }
    }

    private boolean validateInputs(Integer productId, Integer warehouseId,
                                   Integer quantity, Integer allocatedQuantity,
                                   String locationCode, String batchNumber, String expiryDateStr) {

        if (productId == null) {
            showValidationError("请选择有效的商品");
            return false;
        }

        if (warehouseId == null) {
            showValidationError("请选择有效的仓库");
            return false;
        }

        if (quantity == null || quantity < 0) {
            showValidationError("库存数量不能为负数");
            return false;
        }

        if (allocatedQuantity == null || allocatedQuantity < 0) {
            showValidationError("已分配数量不能为负数");
            return false;
        }

        if (allocatedQuantity > quantity) {
            showValidationError("已分配数量不能大于总库存数量");
            return false;
        }

        if (locationCode.isEmpty()) {
            showValidationError("库位编码不能为空");
            return false;
        }

        if (batchNumber.isEmpty()) {
            showValidationError("批次号不能为空");
            return false;
        }

        // 日期验证
        try {
            LocalDate expiryDate = LocalDate.parse(expiryDateStr);
            if (expiryDate.isBefore(LocalDate.now())) {
                showValidationError("过期日期不能早于当前日期");
                return false;
            }
        } catch (DateTimeParseException e) {
            showValidationError("过期日期格式不正确，请使用yyyy-MM-dd格式");
            return false;
        }

        return true;
    }

    private void showValidationError(String message) {
        JOptionPane.showMessageDialog(this, message, "输入验证错误", JOptionPane.WARNING_MESSAGE);
    }

    private boolean addProduct(Integer productId, Integer warehouseId,
                               Integer quantity, Integer allocatedQuantity,
                               String locationCode, String batchNumber, String expiryDateStr) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            connection.setAutoCommit(false);

            String sql = "INSERT INTO inventory(product_id, warehouse_id, quantity, " +
                    "allocated_quantity, location_code, batch_number, expiry_date, " +
                    "last_stock_update, created_time, updated_time) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), NOW())";

            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, productId);
            preparedStatement.setInt(2, warehouseId);
            preparedStatement.setInt(3, quantity);
            preparedStatement.setInt(4, allocatedQuantity);
            preparedStatement.setString(5, locationCode);
            preparedStatement.setString(6, batchNumber);
            preparedStatement.setDate(7, java.sql.Date.valueOf(LocalDate.parse(expiryDateStr)));

            int affectedRows = preparedStatement.executeUpdate();
            connection.commit();

            return affectedRows > 0;
        } catch (SQLException e) {
            try {
                if (connection != null) {
                    connection.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            JOptionPane.showMessageDialog(this, "数据库错误: " + e.getMessage(),
                    "数据库错误", JOptionPane.ERROR_MESSAGE);
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            new AddInvenTory();
        });
    }
}